/*
 * Copyright [2022] [https://www.xiaonuo.vip]
 *
 * Snowy采用APACHE LICENSE 2.0开源协议，您在使用过程中，需要注意以下几点：
 *
 * 1.请不要删除和修改根目录下的LICENSE文件。
 * 2.请不要删除和修改Snowy源码头部的版权声明。
 * 3.本项目代码可免费商业使用，商业使用请保留源码和相关描述文件的项目出处，作者声明等。
 * 4.分发源码时候，请注明软件出处 https://www.xiaonuo.vip
 * 5.不可二次分发开源参与同类竞品，如有想法可联系团队xiaonuobase@qq.com商议合作。
 * 6.若您的项目无法满足以上几点，需要更多功能代码，获取Snowy商业授权许可，请在官网购买授权，地址为 https://www.xiaonuo.vip
 */
package vip.xiaonuo.biz.modular.Englishword.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollStreamUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import edu.stanford.nlp.pipeline.StanfordCoreNLP;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import vip.xiaonuo.biz.core.config.QianWenConfig;
import vip.xiaonuo.biz.modular.Englishword.NLPUtils;
import vip.xiaonuo.biz.modular.Englishword.WordUtils;
import vip.xiaonuo.biz.modular.Englishword.param.*;
import vip.xiaonuo.biz.modular.Englishword.result.BizWordInfoResult;
import vip.xiaonuo.biz.modular.Englishword.result.EnglishArticleResult;
import vip.xiaonuo.biz.modular.Englishword.result.EnglishArticleWithQuestionsResult;
import vip.xiaonuo.biz.modular.Englishword.result.QianWenResult;
import vip.xiaonuo.biz.modular.wordarticle.entity.BizWordArticle;
import vip.xiaonuo.biz.modular.wordarticle.service.BizWordArticleService;
import vip.xiaonuo.common.enums.CommonSortOrderEnum;
import vip.xiaonuo.common.exception.CommonException;
import vip.xiaonuo.common.page.CommonPageRequest;
import vip.xiaonuo.biz.modular.Englishword.entity.BizCet43;
import vip.xiaonuo.biz.modular.Englishword.mapper.BizCet43Mapper;
import vip.xiaonuo.biz.modular.Englishword.service.BizCet43Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 4级单词表Service接口实现类
 *
 * @author Lancer
 * @date 2025/01/09 16:17
 **/
@Service
@Slf4j
public class BizCet43ServiceImpl extends ServiceImpl<BizCet43Mapper, BizCet43> implements BizCet43Service {
    @Autowired
    QianWenConfig qianWenConfig;

    @Autowired
    BizWordArticleService wordArticleService;

    @Autowired
    StanfordCoreNLP stanfordCoreNLP;

    @Override
    public Page<BizCet43> page(BizCet43PageParam bizCet43PageParam) {
        QueryWrapper<BizCet43> queryWrapper = new QueryWrapper<BizCet43>().checkSqlInjection();
        if (ObjectUtil.isAllNotEmpty(bizCet43PageParam.getSortField(), bizCet43PageParam.getSortOrder())) {
            CommonSortOrderEnum.validate(bizCet43PageParam.getSortOrder());
            queryWrapper.orderBy(true, bizCet43PageParam.getSortOrder().equals(CommonSortOrderEnum.ASC.getValue()),
                    StrUtil.toUnderlineCase(bizCet43PageParam.getSortField()));
        } else {
            queryWrapper.lambda().orderByAsc(BizCet43::getWordrank);
        }
        return this.page(CommonPageRequest.defaultPage(), queryWrapper);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void add(BizCet43AddParam bizCet43AddParam) {
        BizCet43 bizCet43 = BeanUtil.toBean(bizCet43AddParam, BizCet43.class);
        this.save(bizCet43);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void edit(BizCet43EditParam bizCet43EditParam) {
        BizCet43 bizCet43 = this.queryEntity(String.valueOf(bizCet43EditParam.getWordrank()));
        BeanUtil.copyProperties(bizCet43EditParam, bizCet43);
        this.updateById(bizCet43);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void delete(List<BizCet43IdParam> bizCet43IdParamList) {
        // 执行删除
        this.removeByIds(CollStreamUtil.toList(bizCet43IdParamList, BizCet43IdParam::getWordrank));
    }

    @Override
    public BizCet43 detail(BizCet43IdParam bizCet43IdParam) {
        return this.queryEntity(String.valueOf(bizCet43IdParam.getWordrank()));
    }

    @Override
    public BizCet43 queryEntity(String id) {
        BizCet43 bizCet43 = this.getById(id);
        if (ObjectUtil.isEmpty(bizCet43)) {
            throw new CommonException("4级单词表不存在，id值为：{}", id);
        }
        return bizCet43;
    }

    @Override
    public BizWordInfoResult dayword(DayWordParam dayWordParam) {
        Boolean fastShotFlag= dayWordParam.getFastShotFlag();
        if (ObjectUtil.isNotEmpty(fastShotFlag)&&fastShotFlag){
           return dayWordSimpleFastShot(dayWordParam.getFastShotId());
        }
        dayWordParam.setWordType("CET4_3");
        // 如果是简单模式，只返回单词
        if (BooleanUtil.isTrue(dayWordParam.getIsSimple())) {
            return daywordSimple(dayWordParam);
        }
        List<BizCet43> bizCet43s = this.getBaseMapper().getRandomWord(dayWordParam.getNumber(), dayWordParam.getWordType());
        BizWordInfoResult result = new BizWordInfoResult();
        result.setDetailsWordList(bizCet43s);
        return result;
    }

    @Override
    public List<EnglishArticleWithQuestionsResult> wordToArticleAndQuestions(WordToArticleAndQuestionsParam dto) {
        String fastShotId = dto.getFastShotId();
        if (ObjectUtil.isNotEmpty(fastShotId)){
            return wordToArticleAndQuestionsFastShot(fastShotId);
        }
        List<String> words = dto.getWords();
        Integer articleNumber = dto.getArticleNumber();
        // 将list转为字符串
        String wordStr = StrUtil.join(",", words);
        // 将{{articleNum}} 替换为文章数量
        QianWenResult qianWenResult = qianWenConfig.sendWordTxt(wordStr,articleNumber);
        String content = qianWenResult.getChoices().get(0).getMessage().getContent();
        log.info("生成的内容 content:{}",content);
        // 1. 生成文章
        // 2. 生成选择题
        List<EnglishArticleWithQuestionsResult> results = WordUtils.parseText(content);
        for (EnglishArticleWithQuestionsResult result : results) {
            result.setArticle(new EnglishArticleResult("",
                    NLPUtils.splitIntoParagraphs(result.getArticle().getContent(),stanfordCoreNLP)));
        }
        return results;
    }

    @Override
    public BizWordInfoResult daywordSimple(DayWordParam dayWordParam) {
        Boolean fastShotFlag= dayWordParam.getFastShotFlag();
        if (ObjectUtil.isNotEmpty(fastShotFlag)&&fastShotFlag){
            return dayWordSimpleFastShot(null);
        }
        BizWordInfoResult result = new BizWordInfoResult();
        BizWordInfoResult bizWordInfoResult = dayword(dayWordParam);
        if (ObjectUtil.isEmpty(bizWordInfoResult)) {
            return result;
        }
        List<String> listWord = bizWordInfoResult.getDetailsWordList().stream().map(BizCet43::getHeadword).collect(Collectors.toList());
        List<String> listId = new ArrayList<>();
        for (BizCet43 bizCet43 : bizWordInfoResult.getDetailsWordList()) {
            Integer wordrank = bizCet43.getWordrank();
            listId.add(String.valueOf(wordrank));
        }
        result.setWordList(listWord);
        result.setWordIdList(listId);
        return result;
    }


//    public Map<Integer,String> dayWordSimpleMap(DayWordParam dayWordParam) {
//        List<BizCet43> bizCet43List = dayword(dayWordParam);
//        if (CollectionUtil.isEmpty(bizCet43List)) {
//            return new HashMap<>();
//        }
//        // 如果key相同，则覆盖
//        return bizCet43List.stream()
//                .collect(Collectors.toMap(BizCet43::getWordrank,
//                        BizCet43::getHeadword, (oldValue, newValue) -> newValue));
//    }

    @Override
    public BizWordInfoResult dayWordSimpleFastShot(String fastShotId) {
        BizWordInfoResult result = new BizWordInfoResult();
        // 从快照数据库中获取今日随机单词
        BizWordArticle bizWordArticle=this.getBaseMapper().dayWordSimpleFastShot(fastShotId);
        String headword = bizWordArticle.getHeadword();
        String wordId = bizWordArticle.getWordId();
        List<String> parseArray = JSON.parseArray(headword, String.class);
        List<String> parseArrayWordId = JSON.parseArray(wordId, String.class);

        result.setWordList(parseArray);
        result.setWordIdList(parseArrayWordId);
        result.setFastShotId(bizWordArticle.getId());
        // 根据单词id获取单词详情
        List<Integer> idList = parseArrayWordId.stream().map(Integer::parseInt).collect(Collectors.toList());
        List<BizCet43> bizCet43List = this.getBaseMapper().selectBatchIds(idList);
        result.setDetailsWordList(bizCet43List);
        return result;
    }

    @Override
    public List<EnglishArticleWithQuestionsResult> wordToArticleAndQuestionsFastShot(String fastShotId) {
        // fastShotId不能为空
        if (StrUtil.isEmpty(fastShotId)) {
            return new ArrayList<>();
        }
        // 从快照数据库中获取今日随机单词对应的文章
        BizWordArticle wordArticle = wordArticleService.getById(fastShotId);
        String article = wordArticle.getArticle();
        // 解析文章
        List<EnglishArticleWithQuestionsResult> results = WordUtils.parseText(article);
        for (EnglishArticleWithQuestionsResult result : results) {
            result.setArticle(new EnglishArticleResult("",
                    NLPUtils.splitIntoParagraphs(result.getArticle().getContent(),stanfordCoreNLP)));
        }
        return results;
    }
}
